package com.oglvip.business.extend.auth;

import com.google.common.collect.Lists;
import com.oglvip.business.consts.common.Consts;
import com.oglvip.business.consts.common.ResponseCode;
import com.oglvip.business.dto.ResponseData;
import com.oglvip.business.remote.service.api.StoreAccountService;
import com.oglvip.business.remote.service.entity.StoreAccount;
import com.oglvip.business.util.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @auther hanchao
 * @date 2016/12/6 23:07
 */
@Component
public class RestAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private StoreAccountService storeAccountService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        if(AuthExceptionHolder.get() != null){
            AuthenticationException authenticationException = AuthExceptionHolder.get();
            AuthExceptionHolder.clear();
            throw authenticationException;
        }
        String password = EncryptUtil.md5Encrypt(String.valueOf(authentication.getCredentials()));
        ResponseData<StoreAccount> responseData = storeAccountService.login(authentication.getName(),password);
        if(responseData.getCode() == ResponseCode.SUCCESS.getCode()){
            //登陆成功
            List<SimpleGrantedAuthority> authorities = null;
            StoreAccount account = responseData.get();
            if(account.getStatus() == 1){
                authorities = Lists.newArrayList(new SimpleGrantedAuthority(Consts.ROLE_PREFIX + Consts.USER));
            }else if(account.getStatus() == 0){
                throw new AuthenticationServiceException("您的审核已经提交，请耐心等待！");
            }else{
                authorities = Lists.newArrayList(new SimpleGrantedAuthority(Consts.ROLE_PREFIX + Consts.USER_UNREVIEW));
            }
            return new UsernamePasswordAuthenticationToken(responseData.get(),password,authorities);
        }
        throw new BadCredentialsException("用户名或密码错误！");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

}
